/**
 * 
 */
package org.rk.core.filesys.controller.file;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.rk.core.common.util.RkObjectUtil;
import org.rk.core.common.util.RkStrUtil;
import org.rk.core.pubServer.controller.BaseController;
import org.rk.core.ueditor.ActionEnter;
import org.rk.core.ueditor.define.AppInfo;
import org.rk.core.ueditor.define.BaseState;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author Cavion(曹仁道)
 * @类描述：
 * 2017年1月3日
 */
public class FileController<T> extends BaseController<T> {

	public @ResponseBody Object ueditorFile(HttpServletRequest request, HttpServletResponse response,MultipartFile mf, String rootPath,String rootUrl) {
		String configPath = this.getClass().getResource("/").getPath();
		ActionEnter ae;
		try {
			if(RkObjectUtil.isEmpty(mf)){
				ae = new ActionEnter(request,rootPath, configPath);
			}else{
				ae = new ActionEnter(request, mf.getInputStream(), mf.getOriginalFilename(), rootPath, configPath);
			}
			String result = ae.exec();
			// 把json字符串转换成json对象
			JSONObject resultJson = JSONObject.parseObject(result);
			if(!RkObjectUtil.isEmpty(mf)){
				resultJson.put("mimeType", mf.getContentType());
			}
			String url=resultJson.getString("url");
			if(RkStrUtil.hasText(url)){
				resultJson.replace("url", "/"+rootUrl+url);
			}
			JSONArray jsonArray=resultJson.getJSONArray("list");
			JSONArray newJsonArray=new JSONArray();
			if(!RkObjectUtil.isEmpty(jsonArray)){
				for (Object object : jsonArray) {
					JSONObject arJson=(JSONObject) object;
					String arUrl=arJson.getString("url");
					if(RkStrUtil.hasText(arUrl)){
						arJson.replace("url", "/"+rootUrl+arUrl);
					}
					newJsonArray.add(arJson);
				}
				resultJson.replace("list", newJsonArray);
			}
			return resultJson;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}
}
